<template>
  <div class="dashboard-container" id="member-app">
    <!-- Employee List Section -->
    <div class="container">
      <div class="tableBar">
        <el-input
            v-model="input"
            placeholder="请输入员工姓名"
            style="width: 250px"
            clearable
            @keyup.enter.native="handleQuery"
        >
          <i
              slot="prefix"
              class="el-input__icon el-icon-search"
              style="cursor: pointer"
              @click="handleQuery"
          ></i>
        </el-input>
        <el-button
            type="primary"
            @click="openDialog('add')"
        >
          + 添加员工
        </el-button>
      </div>
      <el-table
          :data="tableData"
          stripe
          class="tableBox"
      >
        <el-table-column prop="name" label="员工姓名"></el-table-column>
        <el-table-column prop="username" label="账号"></el-table-column>
        <el-table-column prop="phone" label="手机号"></el-table-column>
        <el-table-column label="账号状态">
          <template #default="scope">
            {{ String(scope.row.status) === '0' ? '已禁用' : '正常' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" align="center">
          <template #default="scope">
            <el-button
                type="text"
                size="small"
                @click="openDialog('edit', scope.row.id)"
                :class="{ notAdmin: user !== 'admin' }"
            >
              编辑
            </el-button>
            <el-button
                type="text"
                size="small"
                @click="statusHandle(scope.row)"
                v-if="user === 'admin'"
            >
              {{ scope.row.status == '1' ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          class="pageList"
          :page-sizes="[2]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="counts"
          :current-page.sync="page"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      ></el-pagination>
    </div>

    <!-- Add/Edit Employee Dialog -->
    <el-dialog
        :title="dialogTitle"
        :visible.sync="isDialogVisible"
        width="600px"
    >
      <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
      >
        <el-form-item label="账号:" prop="username">
          <el-input v-model="ruleForm.username" placeholder="请输入账号" maxlength="20"/>
        </el-form-item>
        <el-form-item label="员工姓名:" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入员工姓名" maxlength="20"/>
        </el-form-item>
        <el-form-item label="手机号:" prop="phone">
          <el-input v-model="ruleForm.phone" placeholder="请输入手机号" maxlength="20"/>
        </el-form-item>
        <el-form-item label="性别:" prop="sex">
          <el-radio-group v-model="ruleForm.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="身份证号:" prop="idNumber">
          <el-input v-model="ruleForm.idNumber" placeholder="请输入身份证号" maxlength="20"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { getMemberList, addEmployee, editEmployee, enableOrDisableEmployee, queryEmployeeById } from '@/api/admin/member';
import { checkUserName, checkName, checkPhone, validID } from '@/assets/js/validate';

const input = ref('');
const counts = ref(0);
const page = ref(1);
const pageSize = ref(2);
const tableData = ref([]);
const isDialogVisible = ref(false);
const dialogTitle = ref('');
const actionType = ref('');
const ruleForm = reactive({
  name: '',
  phone: '',
  sex: '男',
  idNumber: '',
  username: '',
});
const user = ref('');

// Form validation rules
const rules = reactive({
  username: [{ required: true, validator: checkUserName, trigger: 'blur' }],
  name: [{ required: true, validator: checkName, trigger: 'blur' }],
  phone: [{ required: true, validator: checkPhone, trigger: 'blur' }],
  idNumber: [{ required: true, validator: validID, trigger: 'blur' }],
});

onMounted(() => {
  init();
  const userInfo = localStorage.getItem('userInfo');
  if (userInfo) {
    user.value = JSON.parse(userInfo).username;
  }
});

// Fetch initial data
const init = async () => {
  const params = {
    page: page.value,
    pageSize: pageSize.value,
    name: input.value || undefined,
  };
  try {
    const res = await getMemberList(params);
    if (String(res.code) === '1') {
      tableData.value = res.data.records || [];
      counts.value = res.data.total;
    }
  } catch (error) {
    ElMessage.error('请求出错了：' + error);
  }
};

// Search and filter employees
const handleQuery = () => {
  page.value = 1;
  init();
};

// Open dialog for add/edit
const openDialog = (type, id = '') => {
  actionType.value = type;
  dialogTitle.value = type === 'add' ? '添加员工' : '编辑员工';
  if (type === 'edit') {
    queryEmployeeById(id).then((res) => {
      if (String(res.code) === '1') {
        Object.assign(ruleForm, res.data);
        ruleForm.sex = res.data.sex === '0' ? '女' : '男';
      } else {
        ElMessage.error(res.msg || '操作失败');
      }
    });
  } else {
    Object.assign(ruleForm, {
      name: '',
      phone: '',
      sex: '男',
      idNumber: '',
      username: '',
    });
  }
  isDialogVisible.value = true;
};

// Close dialog
const closeDialog = () => {
  isDialogVisible.value = false;
};

// Save form data
const submitForm = (formName) => {
  const formRef = formName === 'ruleForm' ? ruleForm : null;
  if (!formRef) return;

  formRef.validate(async (valid) => {
    if (!valid) return;

    const params = {
      ...ruleForm,
      sex: ruleForm.sex === '女' ? '0' : '1',
    };

    try {
      if (actionType.value === 'add') {
        const res = await addEmployee(params);
        if (res.code === 1) {
          ElMessage.success('员工添加成功！');
          closeDialog();
          init();
        } else {
          ElMessage.error(res.msg || '操作失败');
        }
      } else {
        const res = await editEmployee(params);
        if (res.code === 1) {
          ElMessage.success('员工信息修改成功！');
          closeDialog();
          init();
        } else {
          ElMessage.error(res.msg || '操作失败');
        }
      }
    } catch (error) {
      ElMessage.error('请求出错了：' + error);
    }
  });
};

// Change account status
const statusHandle = (row) => {
  const { id, status } = row;
  ElMessageBox.confirm('确认调整该账号的状态?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        try {
          const res = await enableOrDisableEmployee({ id, status: status === 1 ? 0 : 1 });
          if (res.code === 1) {
            ElMessage.success('账号状态更改成功！');
            init();
          } else {
            ElMessage.error(res.msg || '操作失败');
          }
        } catch (error) {
          ElMessage.error('请求出错了：' + error);
        }
      })
      .catch(() => {});
};

// Pagination handlers
const handleSizeChange = (val) => {
  pageSize.value = val;
  init();
};

const handleCurrentChange = (val) => {
  page.value = val;
  init();
};
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.tableBar {
  margin-bottom: 20px;
}

.tableBox {
  margin-bottom: 20px;
}
</style>


<style scoped>
.dashboard-container {
  padding: 20px;
}

.dashboard-container .container {
  background: #fff;
  position: relative;
  z-index: 1;
  padding: 30px 28px;
  border-radius: 4px;
}

.dashboard-container .container .tableBar {
  display: flex;
  margin-bottom: 20px;
  justify-content: space-between;
}

.dashboard-container .container .tableBox {
  width: 100%;
  border: solid 2px #f3f4f7;
  border-radius: 2px;
}

.dashboard-container .container .tableBox .el-image img {
  width: 40px;
  border-radius: 5px;
}

.dashboard-container .container .pageList {
  text-align: center;
  margin-top: 30px;
}

.dashboard-container .container .tableLab .span-btn {
  cursor: pointer;
  display: inline-block;
  font-size: 14px;
  padding: 0 20px;
  color: #818693;
  border-right: solid 1px #d8dde3;
}

.dashboard-container .container .tableLab .el-button {
  margin-left: 10px;
}

.el-table-column--selection .cell {
  padding-left: 10px;
}

/* 添加 */
.addBrand-container .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.addBrand-container .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.addBrand-container .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 160px;
  line-height: 160px;
  text-align: center;
}

.addBrand-container .avatar {
  width: 160px;
  height: 160px;
  display: block;
}

.addBrand-container .el-form--inline .el-form-item__content {
  width: 293px;
}

.addBrand-container .el-input {
  width: 293px;
}

.addBrand-container {
  margin: 30px;
}

.addBrand-container .container {
  position: relative;
  z-index: 1;
  background: #fff;
  padding: 30px;
  border-radius: 4px;
  min-height: 500px;
}

.addBrand-container .container .subBox {
  padding-top: 30px;
  text-align: center;
  border-top: solid 1px #f3f4f7;
}

.flavorBox {
  width: 777px;
}

.flavorBox .addBut {
  background: #ffc200;
  display: inline-block;
  padding: 0px 20px;
  border-radius: 3px;
  line-height: 40px;
  cursor: pointer;
  border-radius: 4px;
  color: #333333;
  font-weight: 500;
}

.flavorBox .flavor {
  border: solid 1px #dfe2e8;
  border-radius: 3px;
  padding: 15px;
  background: #fafafb;
}

.flavorBox .flavor .title {
  color: #606168;
}

.flavorBox .flavor .cont .items {
  display: flex;
  margin: 10px 0;
}

.flavorBox .flavor .cont .items .itTit {
  width: 150px;
  margin-right: 15px;
}

.flavorBox .flavor .cont .items .itTit input {
  width: 100%;
  line-height: 40px;
  border-radius: 3px;
  padding: 0 10px;
}

.flavorBox .flavor .cont .items .labItems {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  border-radius: 3px;
  min-height: 39px;
  border: solid 1px #d8dde3;
  background: #fff;
  padding: 0 5px;
}

.flavorBox .flavor .cont .items .labItems span {
  display: inline-block;
  color: #f19c59;
  margin: 5px;
  line-height: 26px;
  height: 26px;
  padding: 0 10px;
  background: #fdf4eb;
  border-radius: 3px;
  border: solid 1px #fae2cd;
}

.flavorBox .flavor .cont .items .labItems span i {
  cursor: pointer;
  font-style: normal;
}

.flavorBox .flavor .cont .items .labItems .inputBox {
  display: inline-block;
  width: 100%;
  height: 36px;
  line-height: 36px;
  overflow: hidden;
}

.flavorBox .flavor .cont .items .delFlavor {
  display: inline-block;
  padding: 0 10px;
  color: #f19c59;
  cursor: pointer;
}

.addBrand-container .address .el-form-item__content {
  width: 777px !important;
}

.el-button--text {
  font-weight: 400 !important;
  font-size: 13px !important;
}

.el-table td {
  font-size: 13px !important;
}

.el-table .cell,
.el-table th div,
.el-table--border td:first-child .cell,
.el-table--border th:first-child .cell {
  padding-left: 12px;
}


</style>
